#include "gd32f3x0.h"
#include "gd32f310_bsp_adc.h"
#include "systick.h"
#include "wave_analysis.h"

#define ADC_SAMPLETIME_POINT ADC_SAMPLETIME_239POINT5

uint16_t adc_value_raw[ADC_CHANNELS];

void bsp_adc_init(void)
{
    /* enable GPIOC clock */
    rcu_periph_clock_enable(RCU_GPIOA);
    /* enable ADC clock */
    rcu_periph_clock_enable(RCU_ADC);
    /* enable DMA clock */
    rcu_periph_clock_enable(RCU_DMA);
    /* config ADC clock */
    rcu_adc_clock_config(RCU_ADCCK_APB2_DIV6);

    /* config the GPIO as analog mode */
    gpio_mode_set(GPIOA, GPIO_MODE_ANALOG, GPIO_PUPD_NONE, GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7);

    /* ADC_DMA_channel configuration */
    dma_parameter_struct dma_data_parameter;
    /* ADC DMA_channel configuration */
    dma_deinit(DMA_CH0);
    /* initialize DMA single data mode */
    dma_data_parameter.periph_addr = (uint32_t)(&ADC_RDATA);
    dma_data_parameter.periph_inc = DMA_PERIPH_INCREASE_DISABLE;
    dma_data_parameter.memory_addr = (uint32_t)(&adc_value_raw);
    dma_data_parameter.memory_inc = DMA_MEMORY_INCREASE_ENABLE;
    dma_data_parameter.periph_width = DMA_PERIPHERAL_WIDTH_16BIT;
    dma_data_parameter.memory_width = DMA_MEMORY_WIDTH_16BIT;
    dma_data_parameter.direction = DMA_PERIPHERAL_TO_MEMORY;
    dma_data_parameter.number = 1U;
    dma_data_parameter.priority = DMA_PRIORITY_HIGH;
    dma_init(DMA_CH0, &dma_data_parameter);
    dma_circulation_enable(DMA_CH0);
    /* enable DMA channel */
    dma_channel_enable(DMA_CH0);

    nvic_irq_enable(DMA_Channel0_IRQn, 0, 1);
    dma_interrupt_enable(DMA_CH0, DMA_INT_FTF);

    /* ADC continuous function enable */
    adc_special_function_config(ADC_CONTINUOUS_MODE, ENABLE);
    /* ADC scan function enable */
    adc_special_function_config(ADC_SCAN_MODE, ENABLE);
    /* ADC data alignment config */
    adc_data_alignment_config(ADC_DATAALIGN_RIGHT);
    /* ADC channel length config */
    adc_channel_length_config(ADC_REGULAR_CHANNEL, 1U);

    /* ADC regular channel config */
    adc_regular_channel_config(0, ADC_CHANNEL_7, ADC_SAMPLETIME_POINT);

    /* ADC trigger config */
    adc_external_trigger_source_config(ADC_REGULAR_CHANNEL, ADC_EXTTRIG_REGULAR_NONE);
    adc_external_trigger_config(ADC_REGULAR_CHANNEL, ENABLE);

    /* enable ADC interface */
    adc_enable();
    delay_1ms(1U);
    /* ADC calibration and reset calibration */
    adc_calibration_enable();

    /* ADC DMA function enable */
    adc_dma_mode_enable();
    /* ADC software trigger enable */
    adc_software_trigger_enable(ADC_REGULAR_CHANNEL);
}

void DMA_Channel0_IRQHandler(void)
{
    if (dma_interrupt_flag_get(DMA_CH0, DMA_INT_FTF))
    {
        dma_interrupt_flag_clear(DMA_CH0, DMA_INT_FTF);
        wave_analysis();
    }
}
